package com.liusha.quicksand.service;

import com.liusha.quicksand.NotFoundException;
import com.liusha.quicksand.dao.UserRepository;
import com.liusha.quicksand.po.Comment;
import com.liusha.quicksand.po.User;
import com.liusha.quicksand.po.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 一世长安一世欢
 * @Date: 2020/10/24
 * @Time: 1:58
 * @Description: No Description
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Transactional
    @Override
    public void save(User u)throws Exception {
        try {
//            u.setLasttime((int) Instant.now().getEpochSecond());

            u.setCreatetime(new Date());
            userRepository.save(u);

        }catch (Exception no){
            throw no;
        }

    }

    @Override
    public Page<User> findAll(String kw, Pageable pageable) {

        return userRepository.findByKeyWord(kw, pageable);
    }

    @Override
    public User findById(Long userId) {

        return userRepository.findById(userId).get();
    }

    @Override
    public void delete(User u) {

        userRepository.delete(u);
    }

    @Override
    public void deleteById(Long userId) {

        userRepository.deleteById(userId);
    }

    @Transactional
    @Override
    public User saveUser(User user) {

        user.setCreatetime(new Date());
        return userRepository.save(user);
    }

    /***
     *
     * @param user
     * @return
     */
    @Override
    public User checkUsers(UserLogin user) {

        User user1=null;
        //去数据库中通过账号查找用户信息
        Optional<User> optionalUser= userRepository.findByUsername(user.getUsername());
        if (optionalUser.isPresent()){
            user1=optionalUser.get();
            if (user1.getPassword().equals(user.getPassword())){
                return user1;
            }
        }
        return null;
    }
}
